package com.devplatform.service.impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.article.ArticleInteractionsMapper;
import com.devplatform.mapper.article.ArticleMapper;
import com.devplatform.mapper.article.UserArticleCollectMapper;
import com.devplatform.mapper.user.UserMapper;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.user.UserArticleCollect;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.ArticleService;
import com.devplatform.service.article.UserArticleCollectService;
import com.devplatform.util.MessageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jnks03
 * @description 针对表【user_article_collect】的数据库操作Service实现
 * @createDate 2025-09-29 09:38:29
 */
@Service
@RequiredArgsConstructor
public class UserArticleCollectServiceImpl extends ServiceImpl<UserArticleCollectMapper, UserArticleCollect>
        implements UserArticleCollectService {
    private final ArticleMapper articleMapper;
    private final UserMapper userMapper;
    private final ArticleService articleService;
    private final UserArticleCollectMapper collectMapper;
    private final ArticleInteractionsMapper interactionsMapper;
    private final MessageUtil messageUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataVo collect(UserArticleCollect userArticleCollect) {
        Long userId = userArticleCollect.getUserId();
        Long articleId = userArticleCollect.getArticleId();
        LambdaQueryWrapper<UserArticleCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserArticleCollect::getUserId, userId).eq(UserArticleCollect::getArticleId, articleId);
        UserArticleCollect hasCollect = collectMapper.selectOne(queryWrapper);
        if (hasCollect != null) {
            //存在，删除表内数据，互动表数据-1
            collectMapper.deleteById(hasCollect.getId());
            interactionsMapper.decrementCollect(articleId);
            return DataVo.ok("取消收藏成功");
        } else {
            userArticleCollect.setCreateTime(LocalDateTime.now());
            collectMapper.insert(userArticleCollect);
            interactionsMapper.incrementCollect(articleId);

            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                return DataVo.error("文章不存在");
            }
            Long authorId = articleService.getAuthorIdByArticleId(articleId);

            User collector = userMapper.selectById(userId);
            String collectorName = collector != null ? collector.getUsername() : "用户";

            String title = "新收藏通知";
            String content = String.format("用户【%s】收藏了你的文章《%s》", collectorName, article.getTitle());
            Map<String, Object> extraData = new HashMap<>();
            extraData.put("articleId", articleId);
            extraData.put("collectorId", userId);
            messageUtil.sendSystemMessage(authorId, title, content, extraData);
            return DataVo.ok("收藏成功");
        }
    }

    @Override
    public DataVo<Boolean> isCollected(Long userId, Long articleId) {
        LambdaQueryWrapper<UserArticleCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserArticleCollect::getUserId, userId)
                .eq(UserArticleCollect::getArticleId, articleId);

        // 统计符合条件的记录数（>0表示已收藏）
        int count = Math.toIntExact(collectMapper.selectCount(queryWrapper));
        return DataVo.ok(count > 0);
    }
}




